import React from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import Tabs, { TabPane } from '@kuiper-components/tabs';
import NotificationList from './NotificationList';
import s from './Notification.module.css';
import fetch from 'API/fetch';
export default function Notification({ className, onClose, casUrl }) {
	const [showTable, setShowTable] = React.useState('none');
	const [sum, setSum] = React.useState(0);
	const [defaultActiveKey, setDefaultActiveKey] = React.useState('');
	const [count, setCount] = React.useState({
		告警通知: 0,
		漏洞速递: 0,
		服务公告: 0,
	});
	const [identified, setIdentified] = React.useState(true);
	const [isClick, setClick] = React.useState('');
	const [notificationGrouped, setNotificationGrouped] = React.useState({
		告警通知: { count: 0, data: [] },
		漏洞速递: { count: 0, data: [] },
		服务公告: { count: 0, data: [] },
	});
	async function getIdentified() {
		const res = await fetch(`/api/v2/users/user_info`, {
			method: 'GET',
		}).catch(e => {
			return {};
		});
		if (res.code === 200) {
			setIdentified(res.results.identified);
			if (res.results.identified) {
				document.getElementById(
					'kuiper_app'
				).children[0].children[0].style.marginTop = 'unset';
				setClick('');
			} else {
				document.getElementById(
					'kuiper_app'
				).children[0].children[0].style.marginTop = '2.25rem';
			}
		}
	}
	async function getData(taskType) {
		const infoObj = {};
		const countObj = {};
		const resW = await fetch(`/api/v2/mail/warnings/get/mini`, {
			method: 'GET',
		}).catch(e => {
			return {};
		});
		if (resW.code === 200) {
			countObj['告警通知'] = resW.results.warnings?.count || 0;
			infoObj['告警通知'] = resW.results.warnings;
		}
		const vulRes = await fetch(
			`/api/v2/news/list?type=vul&isSendNotification=1`,
			{
				method: 'GET',
			}
		).catch(e => {
			return {};
		});
		const serRes = await fetch(
			`/api/v2/news/list?type=service&isSendNotification=1`,
			{
				method: 'GET',
			}
		).catch(e => {
			return {};
		});
		if (vulRes.code === 200) {
			countObj['漏洞速递'] =
				(vulRes.data.total > 5 ? 5 : vulRes.data.total) || 0;
			infoObj['漏洞速递'] = {
				data: vulRes.data.data
					.map(item => {
						return Object.assign(item, { id: item._id });
					})
					.slice(0, 5),
				count: vulRes.data.total > 5 ? 5 : vulRes.data.total,
			};
		}
		if (serRes.code === 200) {
			countObj['服务公告'] =
				(serRes.data.total > 5 ? 5 : serRes.data.total) || 0;
			infoObj['服务公告'] = {
				data: serRes.data.data
					.map(item => {
						return Object.assign(item, { id: item._id });
					})
					.slice(0, 5),
				count: serRes.data.total > 5 ? 5 : serRes.data.total,
			};
		}
		setCount(countObj);
		setNotificationGrouped(infoObj);
		const sum_ = countObj['告警通知'];
		setSum(sum_);
		setDefaultActiveKey(
			Object.keys(countObj).find(key => {
				return countObj[key] > 0;
			})
		);
	}
	React.useEffect(
		goSet => {
			getData();
			const seT = setInterval(() => {
				if (showTable === 'none') {
					getData();
				}
			}, 30 * 1000);
			return () => {
				clearInterval(seT);
			};
		},
		[showTable]
	);
	React.useEffect(() => {
		getIdentified();
	}, []);
	React.useEffect(() => {
		let seT = null;
		if (isClick) {
			getIdentified();
			clearInterval(seT);
			seT = setInterval(() => {
				if (!identified) {
					getIdentified();
				}
			}, 15 * 1000);
		} else {
			clearInterval(seT);
		}
		return () => {
			clearInterval(seT);
		};
	}, [isClick]);

	const handleMouseOver = () => {
		setShowTable('block');
	};
	const handleMouseOut = () => {
		setShowTable('none');
	};

	return (
		<>
			{!identified && (
				<div className={s.identifiedContent}>
					为保证您的账户及资源的安全，建议您优先完成实名认证。
					<a target="_blank" href={casUrl} onClick={() => setClick('click')}>
						去认证
					</a>
				</div>
			)}
			<div
				className={s.main}
				onMouseEnter={handleMouseOver}
				onMouseLeave={handleMouseOut}
			>
				<div
					className={s.icon}
					style={{ display: sum > 0 ? 'inline' : 'none' }}
				>
					{sum > 99 ? '99+' : sum}
				</div>
				<span className={s.title}>消息</span>
				{
					<div className={s.notificationCentre} style={{ display: showTable }}>
						<header className={s.header}>
							<span>站内消息</span>
							<Link to="/message/notification-centre" onClick={onClose}>
								<span className={s.moreNotifi}>{'更多>'}</span>
							</Link>
						</header>
						{defaultActiveKey && (
							<Tabs defaultActiveKey={defaultActiveKey}>
								{Object.entries(notificationGrouped).map(([type, info]) => {
									const isShow = count[type] > 0 ? 'inline' : 'none';
									return (
										<TabPane
											key={type}
											tab={
												<span className={s.tabName}>
													{type}
													{type === '告警通知' && (
														<span
															className={s.count}
															style={{ display: isShow }}
														>
															{count[type] > 99 ? '99+' : count[type]}
														</span>
													)}
												</span>
											}
										>
											<NotificationList
												notificationList={info}
												onChange={getData}
												type={type}
											/>
										</TabPane>
									);
								})}
							</Tabs>
						)}
					</div>
				}
			</div>
		</>
	);
}

Notification.propTypes = {
	className: PropTypes.string,
	onClose: PropTypes.func,
};

Notification.defaultProps = {
	className: '',
	onClose: () => {},
};
